package net.sf.xoperator.ui.aiml;

import java.io.IOException;

import groovy.lang.Binding;
import groovy.util.GroovyScriptEngine;
import groovy.util.ResourceException;
import groovy.util.ScriptException;
import net.sf.xoperator.rdfxmpp.SPARQLQuery;
import net.sf.xoperator.ui.UIAimlConfiguration;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.openbbs.blackboard.ks.KSExecutionContext;

import bitoflife.chatterbean.Match;

public class GroovyListener extends ExternalListener {

	private Log log = LogFactory.getLog(GroovyListener.class);

	private GroovyScriptEngine gse = null;

	public GroovyListener(String groovyRoot) {
		super("groovy");
		try {
			gse = new GroovyScriptEngine(groovyRoot + "");
		} catch (IOException e) {
			log.error(e);
			throw new RuntimeException(e);
		}
	}

	@Override
	public String perform(Match match, String param) {
		// finding the path to the aiml files
		KSExecutionContext context = ((BlackBoardContext) match.getCallback()
				.getContext()).getContext();
		Binding binding = new Binding();
		binding.setVariable("match", match);
		binding.setVariable("context", new TemplateExectutionContext(((BlackBoardContext) match.getCallback().getContext()).getControl(),context));

		try {
			gse.run(param, binding);

		} catch (ResourceException e) {

			throw new RuntimeException(e);
		} catch (ScriptException e) {
			throw new RuntimeException(e);
		}
		if(binding.getVariable("sparqlresult")!=null && !((String)binding.getVariable("sparqlresult")).isEmpty()){
			context.blackboard().write(
					new SPARQLQuery((String) binding.getVariable("sparqlresult")));
	
		}

		
		return "";
	}

}
